package com.cloudkinto.service.headercontainer.impl;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cloudkinto.common.DicBusinessConstant;
import com.cloudkinto.common.DicBusinessItemConstant;
import com.cloudkinto.common.constant.GlobalConstants;
import com.cloudkinto.common.constant.SysConstant;
import com.cloudkinto.common.exception.BizException;
import com.cloudkinto.common.utils.ExcelUtils;
import com.cloudkinto.common.utils.StringsUtil;
import com.cloudkinto.common.utils.TimeUtils;
import com.cloudkinto.common.web.PageResult;
import com.cloudkinto.common.web.SingleResult;
import com.cloudkinto.dao.*;
import com.cloudkinto.entity.*;
import com.cloudkinto.service.dic.DicBusinessItemService;
import com.cloudkinto.service.dic.vo.LanguageValueEntity;
import com.cloudkinto.service.file.FileService;
import com.cloudkinto.service.finance.vo.IdAndNameEntity;
import com.cloudkinto.service.firstvesselorder.FirstVesselOrderService;
import com.cloudkinto.service.firstvesselorder.vo.FirstVesselOrderPageRes;
import com.cloudkinto.service.headercontainer.HeaderContainerOrderService;
import com.cloudkinto.service.headercontainer.HeaderContainerService;
import com.cloudkinto.service.headercontainer.HeaderPriceItemService;
import com.cloudkinto.service.headercontainer.vo.*;
import com.cloudkinto.service.operate.OperateRecordService;
import com.cloudkinto.service.orderinput.OrderInputService;
import com.cloudkinto.service.orderinput.vo.OrderInputPickupExcelExportVo;
import com.cloudkinto.service.storage.StorageService;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * service实现类
 * </p>
 *
 * @author zhangyy
 * @since 2020-10-26
 */
@Service
@Transactional(rollbackFor = Exception.class)//事务回滚
public class HeaderContainerServiceImpl extends ServiceImpl<HeaderContainerDao, HeaderContainerDo> implements HeaderContainerService {
    @Autowired
    private HeaderContainerDao dao;
    @Autowired
    private HeaderContainerOrderDao containerOrderDao;
    @Autowired
    private StorageService storageService;
    @Autowired
    private ContainerTemplateDao containerTemplateDao;
    @Autowired
    private FirstVesselOrderService firstVesselOrderService;
    @Autowired
    private HeaderContainerOrderService headerContainerOrderService;
    @Autowired
    private HeaderPriceItemService headerPriceItemService;
    @Autowired
    private FirstVesselOrderPackageDao firstVesselOrderPackageDao;
    @Autowired
    private FirstVesselOrderProductDao firstVesselOrderProductDao;
    @Autowired
    private FbaStorageDao fbaStorageDao;
    @Autowired
    private DicBusinessItemDao dicBusinessItemDao;
    @Autowired
    private DicBusinessItemService dicBusinessItemService;
    @Autowired
    private CompanyDao companyDao;
    @Autowired
    private FirstVesselOrderDao firstVesselOrderDao;
    @Autowired
    private ProductInfoDao productInfoDao;
    @Autowired
    private FileService fileService;


    //真正的存储路径
    @Value("${gbc.template.filePath}")
    private String filePath;
    @Autowired
    private OrderInputService orderInputService;
    @Autowired
    private OrderInputPackageDao orderInputPackageDao;
    @Autowired
    private OrderInputProductDao orderInputProductDao;
    @Autowired
    private OperateRecordService operateRecordDao;
    @Autowired
    private StorageServiceProjectDao storageServiceDao;
    @Autowired
    private ExchangeRateDao rateDao;


    @Override
    public SingleResult addInit() {
        Map map = new HashMap();
        List<Map> storageList = new ArrayList<>();
        List<Map> storageOutList = new ArrayList<>();

        Map<String, String> param = new HashMap<>();
        param.put("countryType", "2");
        map.put("storageList", storageService.getList(param));
        param.put("countryType", "1");
        map.put("storageOutList", storageService.getList(param));

        List<Map> containerList = new ArrayList<>();
        List<ContainerTemplateDo> templateDoList = containerTemplateDao.selectList(null);
        if (!CollectionUtils.isEmpty(templateDoList)) {
            templateDoList.forEach(containerTemplateDo -> {
                Map map1 = new HashMap();
                map1.put("id", containerTemplateDo.getId());
                map1.put("value", containerTemplateDo.getContainerCode());
                containerList.add(map1);
            });
        }
        map.put("containerList", containerList);
        List<LanguageValueEntity> shipType = new ArrayList<>();
        shipType.add(new LanguageValueEntity(0, "拼柜"));
        shipType.add(new LanguageValueEntity(1, "整柜"));
        map.put("shipType", shipType);
        map.put("chPortResList", dicBusinessItemService.getDicItemList(DicBusinessConstant.chPort));
        map.put("jpPortResList", dicBusinessItemService.getDicItemList(DicBusinessConstant.jpPort));
        return SingleResult.success(map);
    }

    @Override
    public SingleResult updateStatusInit() {
        return SingleResult.success(dicBusinessItemService.getDicItemList(DicBusinessConstant.headerContainerStatus));
    }

    @Override
    public SingleResult updateStatus(HeaderContainerUpdateStatusReq req, Long currentUserId) {
        HeaderContainerDo headerContainerDo = this.baseMapper.selectById(req.getId());
        headerContainerDo.setStatus(req.getStatus());
        headerContainerDo.setUpdateBy(currentUserId);
        headerContainerDo.setUpdateTime(new Date());
        this.baseMapper.updateById(headerContainerDo);
        updateOrderInputStatus(req, currentUserId);
        return SingleResult.success();
    }

    private void updateOrderInputStatus(HeaderContainerUpdateStatusReq req, Long currentUserId) {
        LambdaQueryWrapper<HeaderContainerOrderDo> orderDoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        orderDoLambdaQueryWrapper.eq(HeaderContainerOrderDo::getHeaderContainerId, req.getId());
        List<HeaderContainerOrderDo> containerOrderDoList = containerOrderDao.selectList(orderDoLambdaQueryWrapper);
        for (HeaderContainerOrderDo orderDo : containerOrderDoList) {
            if (orderDo.getOrderType() == SysConstant.DELETE_FLAG_FALSE) {
                //普通入库订单
                OrderInputDo orderInputDo = orderInputService.getBaseMapper().selectById(orderDo.getFirstVesselOrderId());
                if (orderInputDo != null) {
                    if (req.getStatus() == DicBusinessItemConstant.headerContainerCreated) {
                    } else if (req.getStatus() == DicBusinessItemConstant.headerContainerShipped) {
                        if (orderInputDo.getStatus() < DicBusinessItemConstant.inShipSailed)
                            orderInputDo.setStatus(DicBusinessItemConstant.inShipSailed);
                    } else if (req.getStatus() == DicBusinessItemConstant.headerContainerArrivePort) {
                        if (orderInputDo.getStatus() < DicBusinessItemConstant.inPortArrived)
                            orderInputDo.setStatus(DicBusinessItemConstant.inPortArrived);
                    } else if (req.getStatus() == DicBusinessItemConstant.headerContainerChecking) {
                        if (orderInputDo.getStatus() < DicBusinessItemConstant.inChecking)
                            orderInputDo.setStatus(DicBusinessItemConstant.inChecking);
                    } else if (req.getStatus() == DicBusinessItemConstant.headerContainerPassed) {
                        if (orderInputDo.getStatus() < DicBusinessItemConstant.inCheckPass)
                            orderInputDo.setStatus(DicBusinessItemConstant.inCheckPass);
                    } else if (req.getStatus() == DicBusinessItemConstant.headerContainerOverDue) {
                        if (orderInputDo.getStatus() < DicBusinessItemConstant.inChecking)
                            orderInputDo.setStatus(DicBusinessItemConstant.inChecking);
                    } else if (req.getStatus().longValue() == DicBusinessItemConstant.headerContaineredInStorage) {
                        if (orderInputDo.getStatus() < DicBusinessItemConstant.inPutStorage)
                            orderInputDo.setStatus(DicBusinessItemConstant.inPutStorage);
                    } else {
                        continue;
                    }
                    orderInputDo.setUpdateBy(currentUserId);
                    orderInputDo.setUpdateTime(new Date());
                    OperateRecordDo operateRecordDo = new OperateRecordDo();
                    operateRecordDo.setDeleteFlag(0);
                    operateRecordDo.setThirdId(orderInputDo.getId());
                    operateRecordDo.setType(2);
                    operateRecordDo.setOperateBy(currentUserId);
                    operateRecordDo.setOperateTime(new Date());
                    DicBusinessItemDo itemDo = dicBusinessItemDao.selectById(req.getStatus());
//                    if (itemDo != null)
//                        operateRecordDo.setContent("更新了订单状态为" + itemDo.getDicItemValue());
                    operateRecordDo.setRemarks(JSON.toJSONString(orderInputDo));
                    operateRecordDao.operateAddRecord(SysConstant.OPERATE_UPDATE_FBA_ORDER_STATUS,operateRecordDo.getId(),currentUserId,2);
                    orderInputService.updateById(orderInputDo);
                }
            } else {
                //todo 头程入库订单
            }
        }
    }

    @Override
    public Object add(HeaderContainerAddReq req, Long userId) {
        HeaderContainerDo entityDo = new HeaderContainerDo();
        BeanUtils.copyProperties(req, entityDo);
        if (StringUtils.isNotBlank(req.getDepartureDate())) {
            entityDo.setDepartureDate(TimeUtils.parseDate(req.getDepartureDate(), "yyyy-MM-dd HH:mm"));
        }
        if (StringUtils.isNotBlank(req.getLoadingDate())) {
            entityDo.setLoadingDate(TimeUtils.parseDate(req.getLoadingDate(), "yyyy-MM-dd HH:mm"));
        }
        handlerAddBefore(entityDo, userId);
        entityDo.setStatus(DicBusinessItemConstant.headerContainerCreated);
        entityDo.setCreateBy(userId);
        entityDo.setCreateTime(new Date());
        dao.insert(entityDo);
//        String headerContainerNumber = OrderCodeUtil.getHeaderContainerNumber(entityDo.getId());
//        entityDo.setContainerNumber(headerContainerNumber);
        dao.updateById(entityDo);
        return null;
    }

    @Override
    public synchronized void jointContainer(HeaderContainerDetailAddReq req, boolean flag) {

        //校验是否超标
        if (flag) {
            jointContainerCheck(req);
        }
        //处理从表信息 以及 更新 first_vessel_order表 is_container状态
        for (Long orderId : req.getOrderIds()) {
            HeaderContainerOrderDo headerContainerOrderDo = new HeaderContainerOrderDo();
            headerContainerOrderDo.setHeaderContainerId(req.getId());
            headerContainerOrderDo.setFirstVesselOrderId(orderId);
            headerContainerOrderDo.setDeleteFlag(SysConstant.DELETE_FLAG_FALSE);
            FirstVesselOrderDo firstVesselOrderDo = firstVesselOrderService.getBaseMapper().selectById(orderId);
            if (firstVesselOrderDo != null) {
                firstVesselOrderDo.setIsContainer(SysConstant.DELETE_FLAG_TRUE);
                headerContainerOrderDo.setOrderType(SysConstant.DELETE_FLAG_TRUE);
                firstVesselOrderService.getBaseMapper().updateById(firstVesselOrderDo);
            } else {
                OrderInputDo orderInputDo = orderInputService.getBaseMapper().selectById(orderId);
                orderInputDo.setIsContainer(SysConstant.DELETE_FLAG_TRUE);
                headerContainerOrderDo.setOrderType(SysConstant.DELETE_FLAG_FALSE);
                orderInputService.getBaseMapper().updateById(orderInputDo);
            }
            headerContainerOrderService.getBaseMapper().insert(headerContainerOrderDo);
        }

        //更新主表信息

        updateContainerInfo(req.getId());

    }

    //更新主表信息 po号  箱子规格尺寸等
    private void updateContainerInfo(Long id) {
        LambdaQueryWrapper<HeaderContainerOrderDo> containerOrderWrapper = new LambdaQueryWrapper<>();
        containerOrderWrapper.eq(HeaderContainerOrderDo::getHeaderContainerId, id);
        List<HeaderContainerOrderDo> headerContainerOrderDos = headerContainerOrderService.getBaseMapper().selectList(containerOrderWrapper);
        List<Long> orderList = headerContainerOrderDos.stream().map(HeaderContainerOrderDo::getFirstVesselOrderId).collect(Collectors.toList());
        Set<String> poSet = new HashSet<>();
        int packageCount = 0;
        int productCount = 0;
        double totalVolume = 0;
        double totalWeight = 0;
        for (Long orderId : orderList) {
            FirstVesselOrderDo firstVesselOrderDo = firstVesselOrderService.getBaseMapper().selectById(orderId);
            if (firstVesselOrderDo != null) {
                LambdaQueryWrapper<FirstVesselOrderPackageDo> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(FirstVesselOrderPackageDo::getOrderId, firstVesselOrderDo.getId());
                List<FirstVesselOrderPackageDo> firstVesselOrderPackageDos = firstVesselOrderPackageDao.selectList(wrapper);
                if (!CollectionUtils.isEmpty(firstVesselOrderPackageDos)) {
                    for (FirstVesselOrderPackageDo firstVesselOrderPackageDo : firstVesselOrderPackageDos) {
                        if (StringUtils.isNotBlank(firstVesselOrderPackageDo.getPoNumber())) {
                            poSet.add(firstVesselOrderPackageDo.getPoNumber());
                        }
                        packageCount += firstVesselOrderPackageDo.getCount();
                        totalWeight += firstVesselOrderPackageDo.getWeight() * firstVesselOrderPackageDo.getCount();
                        totalVolume += firstVesselOrderPackageDo.getCount() * firstVesselOrderPackageDo.getLength() * firstVesselOrderPackageDo.getHeight() * firstVesselOrderPackageDo.getWidth() / 1000000;

                        LambdaQueryWrapper<FirstVesselOrderProductDo> productDoLambdaQueryWrapper = new LambdaQueryWrapper<>();
                        productDoLambdaQueryWrapper.eq(FirstVesselOrderProductDo::getPackageId, firstVesselOrderPackageDo.getId());
                        List<FirstVesselOrderProductDo> firstVesselOrderProductDos = firstVesselOrderProductDao.selectList(productDoLambdaQueryWrapper);
                        if (!CollectionUtils.isEmpty(firstVesselOrderProductDos)) {
                            for (FirstVesselOrderProductDo firstVesselOrderProductDo : firstVesselOrderProductDos) {
                                productCount += firstVesselOrderProductDo.getCount() * firstVesselOrderPackageDo.getCount();
                            }
                        }
                    }
                }
            } else {
                OrderInputDo orderInputDo = orderInputService.getBaseMapper().selectById(orderId);
                LambdaQueryWrapper<OrderInputPackageDo> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(OrderInputPackageDo::getOrderInputId, orderInputDo.getId());
                List<OrderInputPackageDo> inOrderPackageDos = orderInputPackageDao.selectList(wrapper);
                if (!CollectionUtils.isEmpty(inOrderPackageDos)) {
                    for (OrderInputPackageDo inOrderPackageDo : inOrderPackageDos) {
                        packageCount += inOrderPackageDo.getPackageCount();
                        totalWeight += inOrderPackageDo.getPackageWeight() * inOrderPackageDo.getPackageCount();

                        LambdaQueryWrapper<OrderInputProductDo> productDoLambdaQueryWrapper = new LambdaQueryWrapper<>();
                        productDoLambdaQueryWrapper.eq(OrderInputProductDo::getPackageId, inOrderPackageDo.getId());
                        List<OrderInputProductDo> firstVesselOrderProductDos = orderInputProductDao.selectList(productDoLambdaQueryWrapper);
                        if (!CollectionUtils.isEmpty(firstVesselOrderProductDos)) {
                            for (OrderInputProductDo firstVesselOrderProductDo : firstVesselOrderProductDos) {
                                productCount += firstVesselOrderProductDo.getCount() * inOrderPackageDo.getPackageCount();
                            }
                        }
                    }
                }
                totalVolume += orderInputDo.getVolume();
            }
        }
        HeaderContainerDo headerContainerDo = this.baseMapper.selectById(id);
        headerContainerDo.setPackageCount(packageCount);
        headerContainerDo.setProductCount(productCount);
        headerContainerDo.setTotalVolume(totalVolume);
        headerContainerDo.setTotalWeight(totalWeight);
//        if (totalVolume>)
        //todo 尺寸超出时自动选择更大的柜子
        this.baseMapper.updateById(headerContainerDo);

    }

    @Override
    public void autoJointContainer(List<Long> ids) {
        for (Long id : ids) {
            //已经拼柜的 不进行拼柜
            LambdaQueryWrapper<HeaderContainerOrderDo> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(HeaderContainerOrderDo::getHeaderContainerId, id);
            int count = headerContainerOrderService.getBaseMapper().selectCount(wrapper);
            if (count > 0) {
                continue;
            }
            handlerContainer(id);
        }
    }

    private void handlerContainer(Long id) {
        HeaderContainerDo headerContainerDo = this.baseMapper.selectById(id);
        ContainerTemplateDo containerTemplateDo = containerTemplateDao.selectById(headerContainerDo.getContainerId());

        List<Long> ids = new ArrayList<>();
        double volume = 0;
        double weight = 0;
        boolean flag = false;

        LambdaQueryWrapper<FirstVesselOrderDo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(FirstVesselOrderDo::getIsContainer, SysConstant.DELETE_FLAG_FALSE)
                .eq(FirstVesselOrderDo::getStorageId, headerContainerDo.getStartStorageId())
                .eq(FirstVesselOrderDo::getFbaStorageId, headerContainerDo.getEndStorageId());
        List<FirstVesselOrderDo> firstVesselOrderDos = firstVesselOrderService.getBaseMapper().selectList(wrapper);
        if (!CollectionUtils.isEmpty(firstVesselOrderDos)) {
            for (FirstVesselOrderDo firstVesselOrderDo : firstVesselOrderDos) {
                LambdaQueryWrapper<FirstVesselOrderPackageDo> packageWrapper = new LambdaQueryWrapper<>();
                packageWrapper.eq(FirstVesselOrderPackageDo::getOrderId, firstVesselOrderDo.getId());
                List<FirstVesselOrderPackageDo> firstVesselOrderPackageDos = firstVesselOrderPackageDao.selectList(packageWrapper);
                if (!CollectionUtils.isEmpty(firstVesselOrderPackageDos)) {
                    for (FirstVesselOrderPackageDo firstVesselOrderPackageDo : firstVesselOrderPackageDos) {
                        volume += firstVesselOrderPackageDo.getCount() * firstVesselOrderPackageDo.getLength() * firstVesselOrderPackageDo.getHeight() * firstVesselOrderPackageDo.getWidth() / 1000000;
                        weight += firstVesselOrderPackageDo.getWeight();

                        if (containerTemplateDo.getVolume() < volume || containerTemplateDo.getWeight() < weight) {
                            flag = true;
                            break;
                        }
                    }
                }
                if (flag) {
                    break;
                }
                ids.add(firstVesselOrderDo.getId());
            }
        }

        HeaderContainerDetailAddReq req = new HeaderContainerDetailAddReq();
        req.setId(id);
        req.setOrderIds(ids);
        jointContainer(req, false);
    }

    private void jointContainerCheck(HeaderContainerDetailAddReq req) {
        HeaderContainerDo headerContainerDo = this.baseMapper.selectById(req.getId());
        ContainerTemplateDo containerTemplateDo = containerTemplateDao.selectById(headerContainerDo.getContainerId());
        double volume = 0;
        double weight = 0;

        //将当前选择的订单 加上之前已经拼柜的订单 计算总的体积 和重量 判断是否超标
        List<FirstVesselOrderPackageDo> firstVesselOrderPackageDos = new ArrayList<>();

        //之前已经拼柜的订单
        LambdaQueryWrapper<HeaderContainerOrderDo> headerContainerOrderWrapper = new LambdaQueryWrapper<>();
        headerContainerOrderWrapper.eq(HeaderContainerOrderDo::getHeaderContainerId, req.getId());
        List<HeaderContainerOrderDo> headerContainerOrderDos = headerContainerOrderService.getBaseMapper().selectList(headerContainerOrderWrapper);
        if (!CollectionUtils.isEmpty(headerContainerOrderDos)) {
            List<Long> orderIds = headerContainerOrderDos.stream().map(headerContainerOrderDo -> {
                return headerContainerOrderDo.getFirstVesselOrderId();
            }).collect(Collectors.toList());
            LambdaQueryWrapper<FirstVesselOrderPackageDo> packageWrapper = new LambdaQueryWrapper<>();
            packageWrapper.in(FirstVesselOrderPackageDo::getOrderId, orderIds);
            List<FirstVesselOrderPackageDo> firstVesselOrderPackageDos1 = firstVesselOrderPackageDao.selectList(packageWrapper);
            if (!CollectionUtils.isEmpty(firstVesselOrderPackageDos1)) {
                firstVesselOrderPackageDos.addAll(firstVesselOrderPackageDos1);
            }
        }
        //当前选择的订单
        LambdaQueryWrapper<FirstVesselOrderPackageDo> packageWrapper = new LambdaQueryWrapper<>();
        packageWrapper.in(FirstVesselOrderPackageDo::getOrderId, req.getOrderIds());
        firstVesselOrderPackageDos.addAll(firstVesselOrderPackageDao.selectList(packageWrapper));


        if (!CollectionUtils.isEmpty(firstVesselOrderPackageDos)) {
            for (FirstVesselOrderPackageDo firstVesselOrderPackageDo : firstVesselOrderPackageDos) {
                volume += firstVesselOrderPackageDo.getCount() * firstVesselOrderPackageDo.getLength() * firstVesselOrderPackageDo.getHeight() * firstVesselOrderPackageDo.getWidth() / 1000000;
                weight += firstVesselOrderPackageDo.getWeight();
            }
        }

        if (containerTemplateDo.getVolume() < volume || containerTemplateDo.getWeight() < weight) {
            throw new BizException(SysConstant.HeaderContainer_Size_Error);
        }

        //验证订单是否已经存在
        for (Long orderId : req.getOrderIds()) {
            LambdaQueryWrapper<HeaderContainerOrderDo> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(HeaderContainerOrderDo::getFirstVesselOrderId, orderId);
            int integer = headerContainerOrderService.getBaseMapper().selectCount(wrapper);
            if (integer > 0) {
                FirstVesselOrderDo firstVesselOrderDo = firstVesselOrderService.getBaseMapper().selectById(orderId);
                throw new BizException(SysConstant.HeaderContainer_Join_Error, firstVesselOrderDo.getOrderNumber());
            }
        }

    }

    //新增校验
    private void addCheck(Object req) {

    }

    //做新增之前要执行的业务定制处理
    private void handlerAddBefore(HeaderContainerDo entityDo, Long userId) {
        entityDo.setDeleteFlag(SysConstant.DELETE_FLAG_FALSE);
    }


    @Override
    public SingleResult updateInit(Long id) {
        Map<String, Object> data = new HashMap<>();
        data.put("detail", dao.selectById(id));
        data.put("initData", addInit().getData());
        return SingleResult.success(data);
    }

    @Override
    public HeaderContainerUpdateReq update(HeaderContainerUpdateReq req, Long userId) {
        if (StringUtils.isNotBlank(req.getBillLadingNumber())) {
            //提单号不能重复
            HeaderContainerDo et = dao.selectOne(new LambdaQueryWrapper<HeaderContainerDo>()
                    .ne(HeaderContainerDo::getId, req.getId())
                    .eq(HeaderContainerDo::getBillLadingNumber, req.getBillLadingNumber()).last(" limit 1"));
            if (et != null) {
                throw new BizException(SysConstant.HeaderContainer_Number_Exist);
            }
        }

        HeaderContainerDo entityDo = dao.selectById(req.getId());
        BeanUtils.copyProperties(req, entityDo);
        entityDo.setDepartureDate(null);
        entityDo.setLoadingDate(null);
        entityDo.setArriveStorageDate(null);
        if (StringUtils.isNotBlank(req.getDepartureDate())) {
            entityDo.setDepartureDate(TimeUtils.parseDate(req.getDepartureDate(), "yyyy-MM-dd HH:mm"));
        }
        if (StringUtils.isNotBlank(req.getLoadingDate())) {
            entityDo.setLoadingDate(TimeUtils.parseDate(req.getLoadingDate(), "yyyy-MM-dd HH:mm"));
        }
        if (StringUtils.isNotBlank(req.getArriveStorageDate())) {
            entityDo.setArriveStorageDate(TimeUtils.parseDate(req.getArriveStorageDate(), "yyyy-MM-dd HH:mm"));
        }
        handlerUpdateBefore(entityDo, userId);
        dao.updateById(entityDo);
        return req;
    }

    //编辑校验
    private void updateCheck(Object req) {

    }

    //做修改之前要执行的业务定制处理
    private void handlerUpdateBefore(HeaderContainerDo entityDo, Long userId) {
    }

    //做修改之后要执行的业务定制处理
    private Object handlerUpdateAfter(HeaderContainerDo entityDo) {
        Object res = new Object();
        BeanUtils.copyProperties(entityDo, res);
        return res;
    }

    @Override
    public int delete(Long id, Long userId) {
        HeaderContainerDo headerContainerDo = this.baseMapper.selectById(id);
        if (headerContainerDo.getStatus() == 2) {
            throw new BizException(SysConstant.HeaderContainer_Delete_Error);
        }
        dao.deleteById(id);

        LambdaQueryWrapper<HeaderContainerOrderDo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(HeaderContainerOrderDo::getHeaderContainerId, id);
        List<HeaderContainerOrderDo> headerContainerOrderDos = headerContainerOrderService.getBaseMapper().selectList(wrapper);

        if (!CollectionUtils.isEmpty(headerContainerOrderDos)) {
            headerContainerOrderDos.forEach(headerContainerOrderDo -> {
                FirstVesselOrderDo firstVesselOrderDo = firstVesselOrderService.getBaseMapper().selectById(headerContainerOrderDo.getFirstVesselOrderId());
                if (firstVesselOrderDo != null) {
                    firstVesselOrderDo.setIsContainer(SysConstant.DELETE_FLAG_FALSE);
                    firstVesselOrderService.getBaseMapper().updateById(firstVesselOrderDo);
                }
            });
        }

        headerContainerOrderService.getBaseMapper().delete(wrapper);
        return 1;
    }

    @Override
    public int deleteVesselOrder(HeaderContainerDeleteVesselOrderReq req, Long userId) {
        HeaderContainerOrderDo containerOrderDo = headerContainerOrderService.getBaseMapper().selectById(req.getOrderId());

        FirstVesselOrderDo firstVesselOrderDo = firstVesselOrderService.getBaseMapper().selectById(containerOrderDo.getFirstVesselOrderId());
        if (firstVesselOrderDo != null) {
            firstVesselOrderDo.setIsContainer(SysConstant.DELETE_FLAG_FALSE);
            firstVesselOrderService.getBaseMapper().updateById(firstVesselOrderDo);
        } else {
            OrderInputDo orderInputDo = orderInputService.getBaseMapper().selectById(containerOrderDo.getFirstVesselOrderId());
            orderInputDo.setIsContainer(SysConstant.DELETE_FLAG_FALSE);
            orderInputService.getBaseMapper().updateById(orderInputDo);
        }
        headerContainerOrderService.getBaseMapper().deleteById(req.getOrderId());

        //更新主表信息
        updateContainerInfo(req.getId());
        return 0;
    }


    @Override
    public List<FirstVesselOrderPageRes> detail(Long id) {
        List<FirstVesselOrderPageRes> resList = new ArrayList<>();

        LambdaQueryWrapper<HeaderContainerOrderDo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(HeaderContainerOrderDo::getHeaderContainerId, id);
        List<HeaderContainerOrderDo> headerContainerOrderDos = headerContainerOrderService.getBaseMapper().selectList(wrapper);
        resList = handlerVesselOderListAfter(headerContainerOrderDos);
        return resList;
    }

    private List<FirstVesselOrderPageRes> handlerVesselOderListAfter(List<HeaderContainerOrderDo> orderDoList) {
        List<FirstVesselOrderPageRes> result = new ArrayList<>();
        if (!CollectionUtils.isEmpty(orderDoList)) {
            orderDoList.forEach(headerContainerOrderDo -> {
                FirstVesselOrderPageRes res = new FirstVesselOrderPageRes();
                if (headerContainerOrderDo.getOrderType() == SysConstant.DELETE_FLAG_TRUE) {
                    FirstVesselOrderDo firstVesselOrderDo = firstVesselOrderDao.selectById(headerContainerOrderDo.getFirstVesselOrderId());
                    res.setId(headerContainerOrderDo.getId());
                    res.setOrderId(firstVesselOrderDo.getId());
                    res.setOrderNumber(firstVesselOrderDo.getOrderNumber());
                    res.setRemark(firstVesselOrderDo.getRemark());
                    res.setCreateTime(firstVesselOrderDo.getCreateTime());
                    res.setResultStatus(getResultStatusStr(firstVesselOrderDo.getResultStatus()));
                    res.setIsLabelling(firstVesselOrderDo.getIsLabelling() == 1 ? "已贴标" : "未贴标");
                    res.setIsLabel(firstVesselOrderDo.getIsLabelling());
                    StorageDo storageDo = storageService.getBaseMapper().selectById(firstVesselOrderDo.getStorageId());
                    if (storageDo != null) {
                        res.setStorage(storageDo.getStorageName());
                    }
                    FbaStorageDo storageOutDo = fbaStorageDao.selectById(firstVesselOrderDo.getFbaStorageId());
                    if (storageOutDo != null) {
                        res.setFbaStorage(storageOutDo.getFbaCode());
                    }
                    res.setStatus(firstVesselOrderDo.getStatus());
                    DicBusinessItemDo businessItemDo = dicBusinessItemDao.selectById(firstVesselOrderDo.getStatus());
                    if (businessItemDo != null) {
                        res.setStatusStr(businessItemDo.getDicItemValue());
                    }
                    businessItemDo = dicBusinessItemDao.selectById(firstVesselOrderDo.getLogisticsType());
                    if (businessItemDo != null) {
                        res.setLogisticsType(businessItemDo.getDicItemValue());
                    }
                    CompanyDo companyDo = companyDao.selectById(firstVesselOrderDo.getCompanyId());
                    if (companyDo != null) {
                        res.setCompanyCode(companyDo.getCompanyCode());
                    }


                    LambdaQueryWrapper<FirstVesselOrderPackageDo> packageDoLambdaQueryWrapper = new LambdaQueryWrapper<>();
                    packageDoLambdaQueryWrapper.eq(FirstVesselOrderPackageDo::getOrderId, firstVesselOrderDo.getId());
                    List<FirstVesselOrderPackageDo> firstVesselOrderPackageDos = firstVesselOrderPackageDao.selectList(packageDoLambdaQueryWrapper);
                    int packageCount = 0;
                    double volume = 0;
                    double weight = 0;
                    if (!CollectionUtils.isEmpty(firstVesselOrderPackageDos)) {
                        for (FirstVesselOrderPackageDo packageDo : firstVesselOrderPackageDos) {
                            packageCount += packageDo.getCount();
                            volume += packageDo.getCount() * packageDo.getLength() * packageDo.getWidth() * packageDo.getHeight() / 1000000;
                            weight += packageDo.getCount() * packageDo.getWeight();
                        }
                    }
                    res.setVolume(numberFormat(volume));
                    res.setPackageCounts(packageCount);
                    res.setProductCount(packageCount);
                    res.setWeight(weight);
                } else {
                    OrderInputDo orderInputDo = orderInputService.getBaseMapper().selectById(headerContainerOrderDo.getFirstVesselOrderId());
                    res.setId(headerContainerOrderDo.getId());
                    res.setOrderId(orderInputDo.getId());
                    res.setOrderNumber(orderInputDo.getOrderInputNumber());
                    res.setSendType(orderInputDo.getCarriageType().intValue());
                    res.setRemark(orderInputDo.getTips());
                    res.setCreateTime(orderInputDo.getCreateTime());
//                    res.setResultStatus(getResultStatusStr(orderInputDo.get));
                    StorageDo storageDo = storageService.getBaseMapper().selectById(orderInputDo.getStorageId());
                    if (storageDo != null) {
                        res.setStorage(storageDo.getStorageName());
                    }
                    FbaStorageDo storageOutDo = fbaStorageDao.selectById(orderInputDo.getFbaStorageId());
                    if (storageOutDo != null) {
                        res.setFbaStorage(storageOutDo.getFbaCode());
                    }
                    res.setStatus(orderInputDo.getStatus());
                    DicBusinessItemDo businessItemDo = dicBusinessItemDao.selectById(orderInputDo.getStatus());
                    if (businessItemDo != null) {
                        res.setStatusStr(businessItemDo.getDicItemValue());
                    }
                    CompanyDo companyDo = companyDao.selectById(orderInputDo.getCompanyId());
                    if (companyDo != null) {
                        res.setCompanyCode(companyDo.getCompanyCode());
                    }
                    LambdaQueryWrapper<OrderInputPackageDo> packageDoLambdaQueryWrapper = new LambdaQueryWrapper<>();
                    packageDoLambdaQueryWrapper.eq(OrderInputPackageDo::getOrderInputId, orderInputDo.getId());
                    List<OrderInputPackageDo> firstVesselOrderPackageDos = orderInputPackageDao.selectList(packageDoLambdaQueryWrapper);
                    int packageCount = 0;
                    int productCount = 0;
                    double weight = 0;
                    if (!CollectionUtils.isEmpty(firstVesselOrderPackageDos)) {
                        for (OrderInputPackageDo packageDo : firstVesselOrderPackageDos) {
                            packageCount += packageDo.getPackageCount();
                            weight += packageDo.getPackageCount() * packageDo.getPackageWeight();
                            LambdaQueryWrapper<OrderInputProductDo> OrderInputProductDoWrapper = new LambdaQueryWrapper<>();
                            OrderInputProductDoWrapper.eq(OrderInputProductDo::getOrderInputId, orderInputDo.getId());
                            List<OrderInputProductDo> productDoList = orderInputProductDao.selectList(OrderInputProductDoWrapper);
                            if (!CollectionUtils.isEmpty(productDoList)) {
                                for (OrderInputProductDo productDo : productDoList) {
                                    productCount = productCount + productDo.getCount() * packageDo.getPackageCount();
                                }
                            }
                        }
                    }
                    res.setSetPriceStatus(getPriceSetStatus(headerContainerOrderDo.getSetPriceFlag()));
                    res.setVolume(numberFormat(orderInputDo.getVolume()));
                    res.setPackageCounts(packageCount);
                    res.setProductCount(productCount);
                    res.setWeight(weight);
                }
                result.add(res);
            });
        }
        return result;
    }

    private String getPriceSetStatus(Integer setPriceFlag) {
        if (setPriceFlag == 1) {
            return "已做账单";
        } else if (setPriceFlag == 2) {
            return "已导出账单";
        }
        return "未设置";
    }

    private String getResultStatusStr(Integer resultStatus) {
        if (resultStatus == null)
            return "";
        if (resultStatus == 1) {
            return "当前订单";
        } else if (resultStatus == 2) {
            return "已完成";
        } else if (resultStatus == 3) {
            return "已退回";
        }
        return "";
    }


    @Override
    public SingleResult pageInit() {
        Map<String, List> resultMap = new HashMap<>();
        List<Map> mapList = new ArrayList<>();
        LambdaQueryWrapper<DicBusinessItemDo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DicBusinessItemDo::getDicBusinessId, DicBusinessConstant.headerContainerStatus);
        List<DicBusinessItemDo> transportType = dicBusinessItemDao.selectList(wrapper);
        if (!CollectionUtils.isEmpty(transportType)) {
            transportType.forEach(e -> {
                Map map = new HashMap();
                map.put("id", e.getId());
                map.put("value", e.getDicItemValue());
                mapList.add(map);
            });
        }
        resultMap.put("statusList", mapList);
        return SingleResult.success(resultMap);
    }

    @Override
    public List<HeaderContainerPageRes> getList(Map<String, String> map) {
        QueryWrapper<HeaderContainerDo> wrapper = queryBuild(map);
        List<HeaderContainerDo> list = this.list(wrapper);
        List<HeaderContainerPageRes> result = handlerListAfter(list);
        return result;
    }

    @Override
    public PageResult getListPage(Map<String, String> map) {
        QueryWrapper<HeaderContainerDo> wrapper = queryBuild(map);
        IPage<HeaderContainerDo> page = pageInit(map);
        page = this.page(page, wrapper);
        List<HeaderContainerPageRes> resList = handlerListAfter(page.getRecords());
        PageResult result = new PageResult(resList, (int) page.getCurrent(), (int) page.getSize(), (int) page.getTotal(), (int) page.getPages());
        result.setMapInfo(getStatusList(map));
        return result;
    }

    @Override
    public void exportPackageInvoice(Long id, HttpServletResponse responseBody) {
        HeaderContainerDo headerContainerDo = dao.selectById(id);
        if (headerContainerDo == null) {
            throw new BizException(SysConstant.HeaderContainer_NotExist);
        }
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("header_container_id", id);
        List<HeaderContainerOrderDo> containerOrderDoList = containerOrderDao.selectList(wrapper);
        if (containerOrderDoList.size() < 1) return;
        List<Long> firstVesselOrderIds = new ArrayList<>();
        List<Long> inputOrderIds = new ArrayList<>();
        for (HeaderContainerOrderDo headerContainerOrderDo : containerOrderDoList) {
            if (headerContainerOrderDo.getOrderType() == 0) {
                inputOrderIds.add(headerContainerOrderDo.getFirstVesselOrderId());
            } else {
                firstVesselOrderIds.add(headerContainerOrderDo.getFirstVesselOrderId());
            }
        }
        List<HeaderContainerInvoiceExportVo> invoiceExportVoList = new ArrayList<>();
        List<HeaderContainerPackageExportVo> packageExportVoList = new ArrayList<>();
        List<HeaderContainerDetailExportVo> detailExportVoList = new ArrayList<>();
//        List<FirstVesselOrderDo> firstVesselOrderDoList = firstVesselOrderDao.selectBatchIds(firstVesselOrderIds);
        List<OrderInputDo> orderInputDoList = orderInputService.getBaseMapper().selectBatchIds(inputOrderIds);
//        firstVesselOrderDoList.add(firstVesselOrderDao.selectById(65L));
//        for (FirstVesselOrderDo orderDo :
//                firstVesselOrderDoList) {
//            QueryWrapper packageWrapper = new QueryWrapper();
//            packageWrapper.eq("order_id", orderDo.getId());
//            List<FirstVesselOrderPackageDo> packageDos = firstVesselOrderPackageDao.selectList(packageWrapper);
//            for (FirstVesselOrderPackageDo packageDo :
//                    packageDos) {
//                QueryWrapper productWrapper = new QueryWrapper();
//                productWrapper.eq("package_id", orderDo.getId());
//                List<FirstVesselOrderProductDo> productDos = firstVesselOrderProductDao.selectList(productWrapper);
//                for (FirstVesselOrderProductDo productDo :
//                        productDos) {
//                    ProductInfoDo productInfoDo = productInfoDao.selectById(productDo.getProductId());
//                    HeaderContainerInvoiceExportVo exportVo = new HeaderContainerInvoiceExportVo();
//                    HeaderContainerPackageExportVo packageExportVo = new HeaderContainerPackageExportVo();
//                    HeaderContainerDetailExportVo detailExportVo = new HeaderContainerDetailExportVo();
//                    exportVo.setCommoditySku(productInfoDo.getCommoditySku());
//                    packageExportVo.setCommoditySku(productInfoDo.getCommoditySku());
//                    detailExportVo.setCommodityName(productInfoDo.getCommodityName());
//                    exportVo.setPackageCount(packageDo.getCount());
//                    packageExportVo.setPackageCount(packageDo.getCount());
//                    detailExportVo.setModel(productInfoDo.getBrandModel());
//                    detailExportVo.setMaterial(productInfoDo.getTextureJp());
//                    exportVo.setTotalCount(packageDo.getCount() * productDo.getCount());
//                    ImageEntity image = new ImageEntity();
//                    if (productInfoDo.getProductPictureFileId() != null) {
//                        image.setData(fileService.getFileBytes(productInfoDo.getProductPictureFileId()));
//                        image.setType(ImageEntity.Data);
//                        image.setHeight(200);
//                        image.setWidth(200);
//                        detailExportVo.setPic(image);
//                    }
//                    packageExportVo.setTotalCount(packageDo.getCount() * productDo.getCount());
//                    if (productInfoDo.getCustomsClearancePrice() == null || productInfoDo.getCustomsClearancePrice() == 0) {
//                        exportVo.setPrice(productInfoDo.getReportPrice());
//                        exportVo.setTotalPrice(productInfoDo.getReportPrice() * exportVo.getTotalCount());
//                    } else {
//                        exportVo.setPrice(productInfoDo.getCustomsClearancePrice());
//                        exportVo.setTotalPrice(productInfoDo.getCustomsClearancePrice() * exportVo.getTotalCount());
//                    }
//                    packageExportVo.setNatureWeight(new BigDecimal(productInfoDo.getWeight() * packageDo.getCount()).setScale(2, RoundingMode.UP).doubleValue());
//                    packageExportVo.setGrossWeight(new BigDecimal(packageDo.getWeight() * packageDo.getCount()).setScale(2, RoundingMode.UP).doubleValue());
//                    packageExportVo.setVolume(numberFormat(packageDo.getLength() * packageDo.getWidth() * packageDo.getHeight()
//                            * packageDo.getCount() / 1000000));
//                    invoiceExportVoList.add(exportVo);
//                    packageExportVoList.add(packageExportVo);
//                    detailExportVoList.add(detailExportVo);
//                }
//            }
//        }
        List<OrderInputPickupExcelExportVo> orderInputPickupExcelExportVos = new ArrayList<>();
        OrderHeaderContainerExportVo containerExportVo = new OrderHeaderContainerExportVo();
        containerExportVo.setBillLadingNumber(headerContainerDo.getBillLadingNumber());
        containerExportVo.setInputDate(TimeUtils.formatDate(headerContainerDo.getArriveStorageDate()));
        containerExportVo.setContainerNo(headerContainerDo.getContainerNumber());
        ContainerTemplateDo templateDo = containerTemplateDao.selectById(headerContainerDo.getContainerId());
        if (templateDo != null)
            containerExportVo.setContainerType(templateDo.getContainerCode());
        int totalPackageCount = 0;
        for (OrderInputDo orderInputDo : orderInputDoList) {
            LambdaQueryWrapper<OrderInputPackageDo> packageDoWrapper = new LambdaQueryWrapper<>();
            packageDoWrapper.eq(OrderInputPackageDo::getOrderInputId, orderInputDo.getId());
            List<OrderInputPackageDo> packageDoList = orderInputPackageDao.selectList(packageDoWrapper);
            if (packageDoList.size() < 1) continue;
            for (OrderInputPackageDo packageDo : packageDoList) {
                OrderInputPickupExcelExportVo pickupExcelExportVo = new OrderInputPickupExcelExportVo();
                pickupExcelExportVo.setOrderNo(orderInputDo.getOrderInputNumber()+"");
                pickupExcelExportVo.setCompanyCode(companyDao.selectById(orderInputDo.getCompanyId()).getCompanyCode());
                pickupExcelExportVo.setPackageCount(packageDo.getPackageCount());
                pickupExcelExportVo.setPackageLength(packageDo.getPackageLenght() + "(  )");
                pickupExcelExportVo.setPackageWeight(packageDo.getPackageWeight() + "(  )");
                pickupExcelExportVo.setPackageWidth(packageDo.getPackageWidth() + "(  )");
                pickupExcelExportVo.setPackageHeight(packageDo.getPackageHeight() + "(  )");
                totalPackageCount = totalPackageCount + packageDo.getPackageCount();
                LambdaQueryWrapper<OrderInputProductDo> productWrapper = new LambdaQueryWrapper<>();
                productWrapper.eq(OrderInputProductDo::getPackageId, packageDo.getId());
                List<OrderInputProductDo> productDoList = orderInputProductDao.selectList(productWrapper);
                if (productDoList.size() < 1) continue;
                if (productDoList.size() == 1) {
                    ProductInfoDo productInfoDo = productInfoDao.selectById(productDoList.get(0).getProductId());
                    if (productInfoDo == null) continue;
                    pickupExcelExportVo.setCommoditySku(productInfoDo.getCommoditySku());
                    pickupExcelExportVo.setStorageSku(productInfoDo.getStorageSku());
//                    pickupExcelExportVo.setProductName(productInfoDo.getProductName());
                    pickupExcelExportVo.setProductCount(productDoList.get(0).getCount());
                } else {
                    pickupExcelExportVo.setCommoditySku("混装");
                    pickupExcelExportVo.setStorageSku("混装");
//                    pickupExcelExportVo.setProductName("混装");
                    pickupExcelExportVo.setProductCount(productDoList.get(0).getCount());
                }
                if (orderInputDo.getFbaTurn() == 0) {
                    pickupExcelExportVo.setOperate("上架");
                } else {
                    FbaStorageDo fbaStorageDo = fbaStorageDao.selectById(orderInputDo.getFbaStorageId());
                    if (fbaStorageDo != null)
                        pickupExcelExportVo.setOperate(fbaStorageDo.getFbaCode());
                    else
                        pickupExcelExportVo.setOperate("转运");
                }
                orderInputPickupExcelExportVos.add(pickupExcelExportVo);
            }
        }
        containerExportVo.setTotalCount(totalPackageCount);
        // 获取模板文件路径
        TemplateExportParams params = new TemplateExportParams(filePath + "入库拣货单.xls");
        //设置sheetName，若不设置该参数，则使用得原本得sheet名称
        Map<String, Object> data = new HashMap<String, Object>();
        data.put("list1", orderInputPickupExcelExportVos);
        data.put("order", containerExportVo);

        // 获取workbook
        Workbook workbook = ExcelExportUtil.exportExcel(params, data);
        try {
            ExcelUtils.downLoadExcel("入库单拣货", responseBody, workbook);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private Map getStatusList(Map<String, String> queryMap) {
        List<Map> result = new ArrayList<>();
        queryMap.put("status", "");

        Map mapTotal = new HashMap();
        List<HeaderContainerDo> list = dao.selectList(queryBuild(queryMap));
        mapTotal.put("count", list.size());
        mapTotal.put("id", "0");
        mapTotal.put("name", StringsUtil.createI18Message("全部"));
        result.add(mapTotal);

        Map<Long, List<HeaderContainerDo>> listMap = list.stream().collect(Collectors.groupingBy(HeaderContainerDo::getStatus));
        LambdaQueryWrapper<DicBusinessItemDo> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(DicBusinessItemDo::getDicBusinessId, DicBusinessConstant.headerContainerStatus);
        for (DicBusinessItemDo itemDo : dicBusinessItemDao.selectList(wrapper1)) {
            Map map1 = new HashMap();
            map1.put("id", itemDo.getId());
            if (listMap.get(itemDo.getId()) != null) {
                map1.put("count", listMap.get(itemDo.getId()).size());
            }
            else {
                map1.put("count", 0);
            }
            map1.put("name", StringsUtil.createI18Message(itemDo.getDicItemValue()));
            result.add(map1);
        }
        Map map2 = new HashMap();
        map2.put("census", result);
        return map2;
    }

    @Override
    public void updatePoNumberHandler(Long id) {
        LambdaQueryWrapper<HeaderContainerOrderDo> containerOrderWrapper = new LambdaQueryWrapper<>();
        containerOrderWrapper.eq(HeaderContainerOrderDo::getHeaderContainerId, id);
        List<HeaderContainerOrderDo> headerContainerOrderDos = headerContainerOrderService.getBaseMapper().selectList(containerOrderWrapper);
        List<Long> orderList = headerContainerOrderDos.stream().map(HeaderContainerOrderDo::getFirstVesselOrderId).collect(Collectors.toList());
        StringBuilder sb = new StringBuilder("");
        for (Long orderId : orderList) {
            FirstVesselOrderDo firstVesselOrderDo = firstVesselOrderService.getBaseMapper().selectById(orderId);
            LambdaQueryWrapper<FirstVesselOrderPackageDo> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(FirstVesselOrderPackageDo::getOrderId, firstVesselOrderDo.getId());
            List<FirstVesselOrderPackageDo> firstVesselOrderPackageDos = firstVesselOrderPackageDao.selectList(wrapper);
            if (!CollectionUtils.isEmpty(firstVesselOrderPackageDos)) {
                for (FirstVesselOrderPackageDo firstVesselOrderPackageDo : firstVesselOrderPackageDos) {
                    sb.append(firstVesselOrderPackageDo.getPoNumber() + ";");
                }
            }
        }

        HeaderContainerDo headerContainerDo = this.baseMapper.selectById(id);
        headerContainerDo.setPoNumberMuti(sb.toString());
        this.baseMapper.updateById(headerContainerDo);
    }

    //查询分页列表之后对列表数据的处理
    private List<HeaderContainerPageRes> handlerListAfter(List<HeaderContainerDo> list) {
        List<HeaderContainerPageRes> result = new ArrayList<>();
        if (!CollectionUtils.isEmpty(list)) {
            list.forEach(headerContainerDo -> {
                HeaderContainerPageRes res = new HeaderContainerPageRes();
                BeanUtils.copyProperties(headerContainerDo, res);
                res.setStatusId(headerContainerDo.getStatus().intValue());
                res.setStorageId(headerContainerDo.getEndStorageId());
                if (headerContainerDo.getTotalVolume() == null) {
                    res.setTotalVolume(0d);
                } else {
                    res.setTotalVolume(numberFormat(headerContainerDo.getTotalVolume()));
                }
                StorageDo storageDo = storageService.getBaseMapper().selectById(headerContainerDo.getStartStorageId());
                if (storageDo != null) {
                    res.setStorage(storageDo.getStorageName());
                }
                StorageDo storageOutDo = storageService.getBaseMapper().selectById(headerContainerDo.getEndStorageId());
                if (storageOutDo != null) {
                    res.setFbaStorage(storageOutDo.getStorageName());
                }
                DicBusinessItemDo startPort = dicBusinessItemDao.selectById(headerContainerDo.getStartPortId());
                if (startPort != null) {
                    res.setStartPort(startPort.getDicItemValue());
                }
                DicBusinessItemDo endPort = dicBusinessItemDao.selectById(headerContainerDo.getEndPortId());
                if (endPort != null) {
                    res.setEndPort(endPort.getDicItemValue());
                }
                res.setArriveStorageDate(TimeUtils.formatDate(headerContainerDo.getArriveStorageDate(), "yyyy-MM-dd HH:mm"));
                res.setDepartureDate(TimeUtils.formatDate(headerContainerDo.getDepartureDate()));
                res.setLicenceDate(TimeUtils.formatDate(headerContainerDo.getLicenceDate()));
                res.setLoadingDate(TimeUtils.formatDate(headerContainerDo.getLoadingDate()));
                ContainerTemplateDo containerTemplateDo = containerTemplateDao.selectById(headerContainerDo.getContainerId());
                if (containerTemplateDo != null) {
                    res.setContainer(containerTemplateDo.getContainerCode());
                    res.setTruckVolume(containerTemplateDo.getVolume());
                    res.setTruckWeight(containerTemplateDo.getWeight());
                }
                DicBusinessItemDo dicBusinessItemDo = dicBusinessItemDao.selectById(headerContainerDo.getStatus());
                if (dicBusinessItemDo != null)
                    res.setStatus(dicBusinessItemDo.getDicItemValue());
                if (StringUtils.isNotBlank(headerContainerDo.getShipBroker()))
                    res.setSetPriceStatus(getPriceSetStatus(Integer.parseInt(headerContainerDo.getShipBroker())));
                result.add(res);
            });
        }
        return result;
    }

    private IPage<HeaderContainerDo> pageInit(Map<String, String> map) {
        IPage<HeaderContainerDo> page = new Page();
        page.setSize(StringUtils.isNotBlank(map.get("pageSize")) ? Long.parseLong(map.get("pageSize")) : 10);
        page.setCurrent(StringUtils.isNotBlank(map.get("current")) ? Long.parseLong(map.get("current")) : 1);
        return page;
    }

    private QueryWrapper<HeaderContainerDo> queryBuild(Map<String, String> map) {
        QueryWrapper<HeaderContainerDo> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(map.get("keyword"))) {
            wrapper.and(i -> {
                i.like("container_number", map.get("keyword")).or().like("po_number_muti", map.get("keyword"));
            });
        }
        if (StringUtils.isNotBlank(map.get("status"))) {
            wrapper.eq("status", map.get("status"));
        }
        if (StringUtils.isNotBlank(map.get("storageId"))) {
            wrapper.eq("start_storage_id", map.get("storageId"));
        }
        if (StringUtils.isNotBlank(map.get("startDate"))) {
            wrapper.ge("create_time", map.get("startDate"));
        }
        if (StringUtils.isNotBlank(map.get("endDate"))) {
            wrapper.le("create_time", map.get("endDate"));
        }
        return wrapper.orderByDesc("id");
    }

    @Override
    public PageResult getWaitOrderList(Map<String, String> map) {
//        LambdaQueryWrapper<FirstVesselOrderDo> firstVesselQueryWrapper = new LambdaQueryWrapper<>();
//        firstVesselQueryWrapper.le(FirstVesselOrderDo::getStatus, DicBusinessItemConstant.seaDispatchShip)
//                .ge(FirstVesselOrderDo::getStatus, DicBusinessItemConstant.seaSubmit)
//                .eq(FirstVesselOrderDo::getIsContainer, 0);
////                .eq(FirstVesselOrderDo::getStorageId, map.get("storageId"));
//        List<FirstVesselOrderDo> firstVesselOrderDoList = firstVesselOrderDao.selectList(firstVesselQueryWrapper);
        QueryWrapper<OrderInputDo> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(map.get("keyword"))) {
            wrapper.and(i -> i.like("order_input_number", map.get("keyword"))
                    .or().like("carriage_track_no", map.get("keyword"))
                    .or().like("tips", map.get("keyword")));
        }
        wrapper.gt("create_time", TimeUtils.getCurrentDateFormat(-365));
        wrapper.le("status", DicBusinessItemConstant.audited);
//        wrapper.eq("storageId",map.get("storageId"));
        wrapper.ge("status", DicBusinessItemConstant.inCreateState);
        wrapper.eq("is_container", 0);//未拼车订单
//        wrapper.eq("send_type", 1);//筋斗云头程
        wrapper.le("carriage_type", 1);//散货或整柜
        if (StringUtils.isNotBlank(map.get("companyId"))) {
            wrapper.eq("company_id", map.get("companyId"));
        }
        wrapper.orderByDesc("id");
        IPage<OrderInputDo> page = new Page();
        page.setSize(StringUtils.isNotBlank(map.get("pageSize")) ? Long.parseLong(map.get("pageSize")) : 10);
        page.setCurrent(StringUtils.isNotBlank(map.get("current")) ? Long.parseLong(map.get("current")) : 1);
        List<OrderInputDo> orderInputDoList = orderInputService.page(page, wrapper).getRecords();
        List<HeaderContainerWaitOrderPageRes> resList = new ArrayList<>();
        if (orderInputDoList != null && orderInputDoList.size() > 0) {
            for (OrderInputDo orderInputDo :
                    orderInputDoList) {
                HeaderContainerWaitOrderPageRes pageRes = new HeaderContainerWaitOrderPageRes();
                pageRes.setId(orderInputDo.getId());
                CompanyDo companyDo = companyDao.selectById(orderInputDo.getCompanyId());
                if (companyDo != null)
                    pageRes.setCompanyCode(companyDo.getCompanyCode());
                pageRes.setCreateTime(orderInputDo.getCreateTime());
                FbaStorageDo fbaStorageDo = fbaStorageDao.selectById(orderInputDo.getFbaStorageId());
                if (fbaStorageDo != null)
                    pageRes.setFbaStorage(fbaStorageDo.getFbaCode());
                pageRes.setFbaStorageId(orderInputDo.getFbaStorageId());
                StorageDo storageDo = storageService.getBaseMapper().selectById(orderInputDo.getStorageId());
                if (storageDo != null)
                    pageRes.setStorage(storageDo.getCode());
                pageRes.setStorageId(orderInputDo.getStorageId());
                pageRes.setOrderNumber(orderInputDo.getOrderInputNumber());
                pageRes.setOrderType(0);
                pageRes.setRemark(orderInputDo.getTips());
                pageRes.setStatus(orderInputDo.getStatus());
                DicBusinessItemDo dicBusinessItemDo = dicBusinessItemDao.selectById(orderInputDo.getStatus());
                if (dicBusinessItemDo != null)
                    pageRes.setStatusStr(dicBusinessItemDo.getDicItemValue());
                LambdaQueryWrapper<OrderInputPackageDo> packageWrapper = new LambdaQueryWrapper<>();
                packageWrapper.eq(OrderInputPackageDo::getOrderInputId, orderInputDo.getId());
                List<OrderInputPackageDo> packageDoList = orderInputPackageDao.selectList(packageWrapper);
                if (packageDoList == null || packageDoList.size() < 1) continue;
                int pacakgeCount = 0, totalCount = 0;
                double totalWeight = 0d;
                for (OrderInputPackageDo packageDo : packageDoList) {
                    pacakgeCount = pacakgeCount + packageDo.getPackageCount();
                    LambdaQueryWrapper<OrderInputProductDo> productWrapper = new LambdaQueryWrapper<>();
                    productWrapper.eq(OrderInputProductDo::getPackageId, packageDo.getId());
                    List<OrderInputProductDo> productDoList = orderInputProductDao.selectList(productWrapper);
                    totalWeight = totalWeight + packageDo.getPackageWeight() * packageDo.getPackageCount();
                    if (productDoList == null || productDoList.size() < 1) continue;
                    for (OrderInputProductDo productDo : productDoList) {
                        totalCount = totalCount + packageDo.getPackageCount() * productDo.getCount();
                    }
                }
                pageRes.setPackageCounts(pacakgeCount);
                pageRes.setProductCount(totalCount);
                pageRes.setVolume(numberFormat(orderInputDo.getVolume()));
                pageRes.setWeight(totalWeight);
                resList.add(pageRes);
            }
        }

        PageResult result = new PageResult(resList, (int) page.getCurrent(), (int) page.getSize(), (int) page.getTotal(), (int) page.getPages());
        return result;
    }

    @Override
    public SingleResult updateLicenceDate(HeaderContainerUpdateLicenceDateReq req) {
        HeaderContainerDo containerOrderDo = baseMapper.selectById(req.getId());
        containerOrderDo.setLicenceDate(req.getLicenceDate());
        boolean b = updateById(containerOrderDo);
        return SingleResult.success();
    }

    @Override
    public SingleResult updateInStorageDate(HeaderContainerUpdateInStorageReq req) {
        HeaderContainerDo containerOrderDo = baseMapper.selectById(req.getId());
        containerOrderDo.setArriveStorageDate(req.getInStorageDate());
        boolean b = updateById(containerOrderDo);
        return SingleResult.success();
    }

    @Override
    public SingleResult updateClearFileId(HeaderContainerUpdateClearFileReq req) {
        HeaderContainerDo containerOrderDo = baseMapper.selectById(req.getId());
        containerOrderDo.setClearFileId(req.getFileId());
        boolean b = updateById(containerOrderDo);
        return SingleResult.success();
    }

    private double numberFormat(double f) {
        BigDecimal b = new BigDecimal(f);
        return b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
    }

    @Override
    public SingleResult setPriceInit(int type, long orderId) {
        LambdaQueryWrapper<StorageServiceProjectDo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<DicBusinessItemDo> dicBusinessItemWrapper = new LambdaQueryWrapper<>();
        dicBusinessItemWrapper.eq(DicBusinessItemDo::getDicBusinessId, DicBusinessConstant.headerContainerFeeProjectStatus);
        List<DicBusinessItemDo> itemDoList = dicBusinessItemDao.selectList(dicBusinessItemWrapper);
        List<HeaderContainerProjectRes> projectResList = new ArrayList<>();

        for (DicBusinessItemDo itemDo : itemDoList) {
            lambdaQueryWrapper.eq(StorageServiceProjectDo::getType, itemDo.getId());//头程订单
            List<StorageServiceProjectDo> projectDoList = storageServiceDao.selectList(lambdaQueryWrapper);
            for (StorageServiceProjectDo storageServiceProjectDo : projectDoList) {
                if (type == 0) {
                    if (storageServiceProjectDo.getId() != 2 && storageServiceProjectDo.getId() != 4 && storageServiceProjectDo.getId() != 10 &&
                            storageServiceProjectDo.getId() != 11 && storageServiceProjectDo.getId() != 12 && storageServiceProjectDo.getId() != 15) {
                        continue;
                    }
                }
                HeaderContainerProjectRes projectRes = new HeaderContainerProjectRes();
                BeanUtils.copyProperties(storageServiceProjectDo, projectRes);
                projectRes.setPrice(storageServiceProjectDo.getPrice());
                DicBusinessItemDo itemDo1 = dicBusinessItemDao.selectById(storageServiceProjectDo.getCurrencyType());
                if (itemDo1 != null)
                    projectRes.setCurrencyTypeName(itemDo1.getDicItemValue());
                if (storageServiceProjectDo.getId() == 10) {
                    projectRes.setProjectContent("请输入货值(USD)");
                    projectRes.setCurrencyTypeName("USD");
                } else if (storageServiceProjectDo.getId() == 11) {
                    projectRes.setProjectContent("请输入关税比(%)");
                    projectRes.setCurrencyTypeName("%");
                }
                if (type == 0 && storageServiceProjectDo.getId() == 4) {
                    projectRes.setProjectContent("头程费");
                    projectRes.setPrice(700);
                    projectRes.setCurrencyTypeName("RMB");
                }
                LambdaQueryWrapper<HeaderPriceItemDo> itemDoLambdaQueryWrapper = new LambdaQueryWrapper<>();
                itemDoLambdaQueryWrapper.eq(HeaderPriceItemDo::getHeaderId, orderId);
                itemDoLambdaQueryWrapper.eq(HeaderPriceItemDo::getProjectId, storageServiceProjectDo.getId());
                HeaderPriceItemDo itemDo2 = headerPriceItemService.getBaseMapper().selectOne(itemDoLambdaQueryWrapper);
                if (itemDo2 != null) {
                    projectRes.setPrice(itemDo2.getPrice());
                    projectRes.setTips(itemDo2.getTips());
                }
                projectResList.add(projectRes);
            }
        }

        return SingleResult.success(projectResList);
    }

    @Override
    public SingleResult setPriceItem(HeaderFeeSetRequest request) {
        HeaderContainerOrderDo containerDo = containerOrderDao.selectById(request.getId());
        HeaderContainerDo containerParentDo = baseMapper.selectById(containerDo.getHeaderContainerId());
        if (containerDo == null) {
            throw new BizException(SysConstant.HeaderContainer_NotExist);
        }
        headerPriceItemService.savePriceItem(0,request);
        containerDo.setSetPriceFlag(1);
        containerOrderDao.updateById(containerDo);
        if (containerParentDo.getType() == 1) {
            containerParentDo.setShipBroker("1");
            updateById(containerParentDo);
        } else {
            LambdaQueryWrapper<HeaderContainerOrderDo> containerWrapper = new LambdaQueryWrapper<>();
            containerWrapper.eq(HeaderContainerOrderDo::getHeaderContainerId, request.getId());
            List<HeaderContainerOrderDo> containerOrderDoList = containerOrderDao.selectList(containerWrapper);
            if (containerOrderDoList.size() > 0) {
                long noSetCount = containerOrderDoList.stream().filter(headerContainerOrderDo -> headerContainerOrderDo.getSetPriceFlag() < 1)
                        .count();
                long exportCount = containerOrderDoList.stream().filter(headerContainerOrderDo -> headerContainerOrderDo.getSetPriceFlag() > 1)
                        .count();
                if (noSetCount > 0) {//未设置费用的子列表数大于0时，主订单改为未设置费用状态
                    containerParentDo.setShipBroker("0");
                } else if (exportCount == containerOrderDoList.size()) {
                    containerParentDo.setShipBroker("2");
                } else {
                    containerParentDo.setShipBroker("1");
                }
                updateById(containerParentDo);
            }
        }
        return SingleResult.success();
    }

    @Override
    public void exportHeaderFeePage(Long orderId, HttpServletResponse response) {
        HeaderContainerOrderDo containerOrderDo = containerOrderDao.selectById(orderId);
        if (containerOrderDo == null) {
            throw new BizException(SysConstant.HeaderContainer_NotExist);
        }
        HeaderContainerDo containerDo = dao.selectById(containerOrderDo.getHeaderContainerId());
        LambdaQueryWrapper<HeaderPriceItemDo> priceItemDoWrapper = new LambdaQueryWrapper<>();
        priceItemDoWrapper.eq(HeaderPriceItemDo::getHeaderId, containerOrderDo.getId());
        List<HeaderPriceItemDo> priceItemDoList = headerPriceItemService.getBaseMapper().selectList(priceItemDoWrapper);
        List<HeaderPriceItemPartExportVo> priceItemPartExportVoList = new ArrayList<>();
        if (priceItemDoList == null || priceItemDoList.size() < 1) {
            throw new BizException(SysConstant.HeaderContainer_NoFeeDetail);
        }
        if (containerDo == null) {
            throw new BizException(SysConstant.HeaderContainer_NotExist);
        }
        double totalFee = 0;
        double jpyRate = getRate(DicBusinessItemConstant.CurrencyTypeJpy);//头程账单加税点5个点
        double usdRate = getRate(DicBusinessItemConstant.CurrencyTypeUsd);//头程账单加税点1个点
        int index = 0;
        OrderInputDo orderInputDo = orderInputService.getBaseMapper().selectById(containerOrderDo.getFirstVesselOrderId());
        if (orderInputDo == null) {
            throw new BizException(SysConstant.HeaderContainer_Order_NotMatch);
        }
        double currentRmdFee = 0;
        for (HeaderPriceItemDo itemDo : priceItemDoList) {
            StorageServiceProjectDo projectDo = storageServiceDao.selectById(itemDo.getProjectId());
            if (projectDo == null) continue;
            HeaderPriceItemPartExportVo partExportVo = new HeaderPriceItemPartExportVo();
            if (orderInputDo.getCarriageType() == 0) {
                partExportVo.setUnit(dicBusinessItemDao.selectById(projectDo.getCurrencyType()).getDicItemValue());
                partExportVo.setProject(projectDo.getProjectContent());
                if (itemDo.getProjectId() == 2) {
                    partExportVo.setPrice(itemDo.getPrice().intValue());
                    partExportVo.setTaxPrice((int) ((double) (itemDo.getPrice() * 0.1D)));
                    partExportVo.setTotalPrice(partExportVo.getPrice() + partExportVo.getTaxPrice());
                    partExportVo.setTips(itemDo.getTips());
                } else if (itemDo.getProjectId() == 10) {//货值
                    int value = (int) (numberFormat((containerOrderDo.getValue() * (1 + containerOrderDo.getRate() / 100)) * 0.1 * usdRate / jpyRate));
                    partExportVo.setPrice(value);
                    partExportVo.setTotalPrice(value);
                } else if (itemDo.getProjectId() == 11) {//关税
                    int value = (int) (containerOrderDo.getValue() * containerOrderDo.getRate() / 100 * usdRate / jpyRate);
                    partExportVo.setPrice(value);
                    partExportVo.setTotalPrice(value);
                } else if (itemDo.getProjectId() == 4) {//海运费
                    itemDo.setTips(itemDo.getTips() + " " + orderInputDo.getVolume() + "m³");
                    partExportVo.setPrice((int) (itemDo.getPrice().doubleValue()));
                    partExportVo.setUnit("RMB");
                    projectDo.setCurrencyType(DicBusinessItemConstant.CurrencyTypeRmb + "");
                    partExportVo.setTotalPrice((int) (partExportVo.getPrice() * orderInputDo.getVolume()) + partExportVo.getTaxPrice());
                } else {
                    partExportVo.setPrice((int) (itemDo.getPrice().doubleValue()));
                    partExportVo.setTaxPrice((int) ((double) (itemDo.getPrice() * 0.1D)));
                    partExportVo.setTotalPrice(partExportVo.getPrice() + partExportVo.getTaxPrice());
                }
                partExportVo.setTips(itemDo.getTips());

            } else {
                if (itemDo.getProjectId() == 4 || itemDo.getProjectId() == 16) {
                    ContainerTemplateDo templateDo = containerTemplateDao.selectById(containerDo.getContainerId());
                    if (templateDo != null)
                        partExportVo.setProject(projectDo.getProjectContent() + "(" + templateDo.getContainerCode() + ")");
                } else {
                    partExportVo.setProject(projectDo.getProjectContent());
                }
                if (itemDo.getProjectId() == 10) {
                    partExportVo.setPrice((int) ((double) (containerOrderDo.getValue() * (1 + containerOrderDo.getRate() / 100)) * 0.1 * usdRate / jpyRate));
                } else if (itemDo.getProjectId() == 11) {
                    partExportVo.setPrice((int) (double) (containerOrderDo.getValue() * containerOrderDo.getRate() / 100 * usdRate / jpyRate));

                } else {
                    partExportVo.setPrice(itemDo.getPrice().intValue());
                }
                partExportVo.setProject(projectDo.getProjectContent());
                if (itemDo.getTaxFlag() == 0) {
                    partExportVo.setTaxPrice((int) ((double) (itemDo.getPrice() * 0.1D)));
                }
                partExportVo.setUnit(dicBusinessItemDao.selectById(projectDo.getCurrencyType()).getDicItemValue());
                partExportVo.setTotalPrice(partExportVo.getPrice() + partExportVo.getTaxPrice());
            }
            partExportVo.setTips(itemDo.getTips());
            if (projectDo.getCurrencyType().equals(DicBusinessItemConstant.CurrencyTypeRmb.toString())) {
                currentRmdFee = partExportVo.getTotalPrice();
            } else if (projectDo.getCurrencyType().equals(DicBusinessItemConstant.CurrencyTypeUsd.toString())) {
                currentRmdFee = numberFormat(partExportVo.getTotalPrice() * usdRate);
            } else {
                currentRmdFee = numberFormat(partExportVo.getTotalPrice() * jpyRate);
            }
            totalFee = currentRmdFee + totalFee;
            index++;
            partExportVo.setIndex(index);
            priceItemPartExportVoList.add(partExportVo);
        }
        // 获取模板文件路径
        TemplateExportParams params = new TemplateExportParams(filePath + "头程账单.xlsx");
        //设置sheetName，若不设置该参数，则使用得原本得sheet名称
        Map<String, Object> data = new HashMap<String, Object>();
        data.put("list", priceItemPartExportVoList);
        data.put("totalFee", numberFormat(totalFee));
        data.put("jpRate", numberFormat(jpyRate));
        data.put("usRate", numberFormat(usdRate));
        DicBusinessItemDo itemDo = dicBusinessItemDao.selectById(containerDo.getEndPortId());
        if (itemDo != null)
            data.put("portJp", itemDo.getDicItemValue());
        DicBusinessItemDo portCH = dicBusinessItemDao.selectById(containerDo.getStartPortId());
        if (portCH != null)
            data.put("portCh", portCH.getDicItemValue());

        // 获取workbook
        Workbook workbook = ExcelExportUtil.exportExcel(params, data);
        try {
            ExcelUtils.downLoadExcel("头程账单", response, workbook);
        } catch (IOException e) {
            e.printStackTrace();
        }
        containerOrderDo.setSetPriceFlag(2);
        containerOrderDao.updateById(containerOrderDo);
        if (containerDo.getType() == 1) {
            containerDo.setShipBroker("2");
            updateById(containerDo);
        } else {
            LambdaQueryWrapper<HeaderContainerOrderDo> containerWrapper = new LambdaQueryWrapper<>();
            containerWrapper.eq(HeaderContainerOrderDo::getHeaderContainerId, containerOrderDo.getHeaderContainerId());
            List<HeaderContainerOrderDo> containerOrderDoList = containerOrderDao.selectList(containerWrapper);
            if (containerOrderDoList.size() > 0) {
                long noSetCount = containerOrderDoList.stream().filter(headerContainerOrderDo -> headerContainerOrderDo.getSetPriceFlag() < 1)
                        .count();
                long exportCount = containerOrderDoList.stream().filter(headerContainerOrderDo -> headerContainerOrderDo.getSetPriceFlag() > 1)
                        .count();
                if (noSetCount > 0) {//未设置费用的子列表数大于0时，主订单改为未设置费用状态
                    containerDo.setShipBroker("0");
                } else if (exportCount == containerOrderDoList.size()) {
                    containerDo.setShipBroker("2");
                } else {
                    containerDo.setShipBroker("1");
                }
                updateById(containerDo);
            }
        }
    }

    private double getRate(long type) {
        //实时汇率
        QueryWrapper<ExchangeRateDo> wrapper = new QueryWrapper();
        wrapper.orderByDesc("id");
        wrapper.eq("type", type);
        wrapper.last("limit 1");
        ExchangeRateDo exchangeRateDo = rateDao.selectOne(wrapper);
        return exchangeRateDo.getRate();
    }

}
